package com.kc.sjwh.other;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * 动态配置项
 * @author zgh
 *
 */
public class Cfg {
	static Logger logger = Logger.getLogger(Cfg.class);
	
	//singleton
	private static Cfg inst = new Cfg();
	public static Cfg getInst() {
		return inst;
	}
	private Cfg() {
	}
	
	private String webTitle;
	private String appCode;
	private String adminPwd;//管理员密码
	private int jqxzLen;
	private int dwLen;
	private String jqxzLevCode;
	private String dwLevCode;
	private String rootDwdm;
	
	public String getAppCode() {
		return appCode;
	}
	public String getRootDwdm() {
		return rootDwdm;
	}
	public void setRootDwdm(String rootDwdm) {
		this.rootDwdm = rootDwdm;
	}
	public String getWebTitle() {
		return webTitle;
	}
	public void setWebTitle(String webTitle) {
		this.webTitle = webTitle;
	}
	public void setAppCode(String appCode) {
		this.appCode = appCode;
	}
	public String getAdminPwd() {
		return adminPwd;
	}
	public void setAdminPwd(String adminPwd) {
		this.adminPwd = adminPwd;
	}
	public int getJqxzLen() {
		return jqxzLen;
	}
	public void setJqxzLen(int jqxzLen) {
		this.jqxzLen = jqxzLen;
	}
	public int getDwLen() {
		return dwLen;
	}
	public void setDwLen(int dwLen) {
		this.dwLen = dwLen;
	}
	public String getJqxzLevCode() {
		return jqxzLevCode;
	}
	public void setJqxzLevCode(String jqxzLevCode) {
		this.jqxzLevCode = jqxzLevCode;
	}
	public String getDwLevCode() {
		return dwLevCode;
	}
	public void setDwLevCode(String dwLevCode) {
		this.dwLevCode = dwLevCode;
	}
	
	public void load() {
		BufferedReader r = null;
		try {
			r = new BufferedReader(
				new InputStreamReader(
					new FileInputStream(getRootDir()+"cfg.txt"), "utf-8"
				)
			);
			
			Map m = new HashMap();
			String line = null;
			while((line = r.readLine()) != null) {
				this.handleLine(m, line);
			}
			BeanUtils.populate(inst, m);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				r.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void handleLine(Map m, String line) {
		if(StringUtils.isNotEmpty(line)) {
			line = line.trim();
			if(!line.startsWith("#")) {
				String key = line.substring(0, line.indexOf("="));
				String val = line.substring(line.indexOf("=")+1);
				if(StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(val)) {
					key = key.trim();
					val = val.trim();
					m.put(key, val);
					logger.info(key+"="+val);
				}
			}
		}
	}
	
	private String getRootDir() {
		return Thread.currentThread().getContextClassLoader().getResource("").getPath();
	}
	
}
